package day16;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class TcpServer {
    public static void main(String[] args)throws Exception {
        // 创建服务器对象
        ServerSocket server = new ServerSocket(8888);
        System.out.println("服务器："+server);
        // 等待客户端连接
        Socket client = server.accept();
        System.out.println("客户端连接成功："+client);
        // 创建io流对象
        InputStream is = client.getInputStream();
        OutputStream os = client.getOutputStream();
        // 服务器端接收客户端发送的内容
        byte[] b = new byte[1024];
        int length = is.read(b);
        if(length != -1){
            // 输出读取的内容
            System.out.println("客户端发送的内容："+new String(b,0,length));
        }
        String string = "Hello Client,我是Server";
        os.write(string.getBytes());
        // 关闭资源 处理异常 注意判空
        is.close();
        os.close();
        client.close();
        server.close();
    }
}
